app.factory("httpService", [
  "$http", "$q", "$rootScope", "ENV", "$ionicLoading", 'loading',
  function($http, $q, $rootScope, ENV, $ionicLoading, loading) {
      var httpService, methods;
      methods = ['post', 'put'];
      httpService = function(url, data, method, cache) {
          var config, q;
          q = $q.defer();
          config = {
              method: method || "get",
              url: ENV.api + url,
              timeout: time_out,
              cache: cache || false,
              headers: {
                  "Content-Type": "application/json"
              }
          };
          if (methods.indexOf(method) !== -1) {
              config.data = data;
          } else {
              config.params = data;
          }
          loading.show();
          $http(config).success(function(data, status, headers, config) {
              q.resolve({
                  data: data,
                  code: parseInt(status, 10)
              });
          }).error(function(data, status, headers, config) {
              console.log('data', data, status, headers, config);
              return q.reject(data);
          })["finally"](function() {
              $rootScope.$broadcast("scroll.refreshComplete");
              $rootScope.$broadcast("scroll.infiniteScrollComplete");
              loading.hide();
          });
          return q.promise;
      };
      return {
          query: httpService
      };
  }
]);
//上传图片到七牛云
app.factory('camera', [
    '$ionicActionSheet', '$cordovaCamera', '$q', 'httpService', 'loading', 'ENV', '$cordovaFileTransfer',
    function($ionicActionSheet, $cordovaCamera, $q, httpService, loading, ENV, $cordovaFileTransfer) {
        var getPicture, options, showAction;
        options = {
            quality: 100,
            allowEdit: false,
            targetWidth: 666,
            targetHeight: 666,
            saveToPhotoAlbum: false
        };
        getPicture = function(opt) {
            var q;
            q = $q.defer();
            if (opt === 0) {
                options.sourceType = Camera.PictureSourceType.CAMERA;
            } else {
                options.sourceType = Camera.PictureSourceType.PHOTOLIBRARY;
            }
            options.destinationType = Camera.DestinationType.FILE_URI;
            options.encodingType = Camera.EncodingType.JPEG;
            options.popoverOptions = CameraPopoverOptions;
            document.addEventListener('deviceready', (function() {
                $cordovaCamera.getPicture(options).then((function(imageUrl) {
                    q.resolve(imageUrl);
                }), function(err) {
                    q.reject(err);
                });
            }), false);
            return q.promise;
        };
        showAction = function(opt) {
            var hideSheet, q;
            opt = opt || 1;
            q = $q.defer();
            cordova.plugins.Keyboard.close();
            hideSheet = $ionicActionSheet.show({
                buttons: [{
                    text: '相机'
                }, {
                    text: '图库'
                }],
                titleText: '图片来源',
                cancelText: '取消',
                cancel: function() {},
                buttonClicked: function(index) {
                    hideSheet();
                    getPicture(index).then(function(fileURL) {
                        // q.resolve(res);
                        if (opt == 'fileURL') {
                            q.resolve(fileURL);
                        } else {
                            httpService.query('upload/uploadToken').then(function(res) {
                                var date, fail, ft, key, options, params, random_int, win;
                                if (res.code === 200) {
                                    win = function(r) {
                                        q.resolve(res.data.qndomain + JSON.parse(r.response).key);
                                    };
                                    fail = function(error) {
                                        q.reject(JSON.stringify(error));
                                    };
                                    options = new FileUploadOptions();
                                    options.fileKey = 'file';
                                    options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
                                    date = function() {
                                        var date_str;
                                        date_str = '';
                                        date = new Date();
                                        date_str += date.getFullYear();
                                        date_str += date.getMonth() + 1;
                                        date_str += date.getDate();
                                        date_str += date.getHours();
                                        date_str += date.getMinutes();
                                        date_str += date.getSeconds();
                                        return date_str;
                                    };
                                    random_int = parseInt(Math.random() * 1000000);
                                    key = 'usr_app_' + ENV.appId + '_msgimg_' + date() + random_int;
                                    params = {
                                        key: key,
                                        token: res.data.upToken,
                                        x: {
                                            variable: random_int
                                        }
                                    };
                                    options.params = params;
                                    ft = new FileTransfer();
                                    ft.upload(fileURL, 'http://upload.qiniu.com/', win, fail, options);
                                } else {
                                    loading.prompt('网络异常!');
                                }
                            });
                        }
                    });
                }
            });
            return q.promise;
        };
        return {
            getPicture: showAction
        };
    }
]);

app.factory('loading', [
    '$ionicLoading', '$timeout',
    function($ionicLoading, $timeout) {
        var hide, prompt, show;
        show = function() {
            $ionicLoading.show({
                template: '<ion-spinner icon="bubbles"></ion-spinner><br/>加载中...',
                noBackdrop: true,
                delay: 1000
            });
        };
        hide = function() {
            $ionicLoading.hide();
        };
        prompt = function(template, time) {
            $ionicLoading.hide();
            time = time || 1000;
            $ionicLoading.show({
                template: template,
                noBackdrop: true,
                duration: time
            });
        };
        return {
            show: show,
            hide: hide,
            prompt: prompt
        };
    }
]);

app.factory('popup', [
    '$ionicPopup', '$timeout',
    function($ionicPopup, $timeout) {
        var alert, confirm, show;
        show = function(template, time) {
            var myPopup;
            time = time || 1000;
            myPopup = $ionicPopup.show({
                template: template
            });
            $timeout((function() {
                myPopup.close();
            }), time);
        };
        confirm = function(template, ok) {
            var confirmPopup;
            confirmPopup = $ionicPopup.confirm({
                template: template || '是否保存？',
                cancelText: '取消',
                okText: ok || '确定'
            });
            return confirmPopup;
        };
        alert = function(template) {
            $ionicPopup.alert({
                template: template || '',
                okText: '确定'
            });
        };
        return {
            show: show,
            confirm: confirm,
            alert: alert
        };
    }
]);

// 版本升级
app.factory('updateAppVersion', [
    'httpService', 'popup', '$window', '$cordovaFileTransfer', '$cordovaFileOpener2', 'version', 'loading', '$rootScope', '$timeout', '$ionicPopup',
    function(httpService, popup, $window, $cordovaFileTransfer, $cordovaFileOpener2, version, loading, $rootScope, $timeout, $ionicPopup) {
        var checkApp, first, uuid;
        uuid = function() {
            var hexDigits, i, s;
            uuid = void 0;
            s = [];
            hexDigits = '0123456789abcdef';
            i = 0;
            while (i < 36) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                i++;
            }
            s[14] = '4';
            s[19] = hexDigits.substr(s[19] & 0x3 | 0x8, 1);
            s[8] = s[13] = s[18] = s[23] = '-';
            uuid = s.join('');
            return uuid;
        };
        first = 1;
        checkApp = function() {
            if (ionic.Platform.isAndroid()) {
                httpService.query('appversion', {
                    versionNo: version
                }).then(function(res) {
                    if (res.code === 200) {
                        if (res.data.versioncode !== version && parseInt(res.data.isupdate, 10) === 1) {
                            popup.confirm('发现新版是否更新？').then(function(bool) {
                                if (bool) {
                                    $window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, (function(r) {
                                        var options, targetPath, trushHosts;
                                        targetPath = r.toURL() + 'freeapp.apk';
                                        trushHosts = true;
                                        options = {};
                                        var myPopup = $ionicPopup.show({
                                            template: '<ion-spinner icon="bubbles"></ion-spinner><br/>{{downloadProgress}}% 下载中...'
                                        });
                                        $cordovaFileTransfer.download(res.data.appurl + '?randam=' + uuid(), targetPath, options, trushHosts).then(function(result) {
                                            $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive').then((function() {
                                                myPopup.close();
                                            }), function() {});

                                        }, function(error) {
                                            console.log('error', error);
                                        }, function(progress) {
                                            $timeout(function() {
                                                $rootScope.downloadProgress = parseInt((progress.loaded / progress.total) * 100, 10);
                                            });
                                        });
                                    }), function(error) {
                                        console.log(error);
                                    });
                                }
                            });
                        } else {
                            if (first !== 1) {
                                loading.prompt('当前已是最新版！');
                            }
                        }
                        ++first;
                    }
                });
            }
        };
        return {
            check: checkApp
        };
    }
]);

app.factory('zmq', [
    '$q', '$rootScope', '$timeout', 'loading', 'httpService', 'ENV', 'md5', '$localStorage',
    function($q, $rootScope, $timeout, loading, httpService, ENV, md5, $localStorage) {
        var init, notification, receive, send, stop, tcp, userPushToken, appid = ENV.uuid.toString();


        document.addEventListener('deviceready', function() {
            if (ionic.Platform.platform() == 'ios') {
                window.ZMQPlugin.getDeviceToken(function(success) {
                    userPushToken = JSON.parse(success).deviceToken;
                    // alert(JSON.stringify(success));
                }, function(error) {
                    // alert(JSON.stringify(error));
                });
            }
        });

        // 从后台获取tcp
        getTcp = function(tcp_url) {
            var q = $q.defer();
            var p_url = 'MmMessage/' + tcp_url;
            if (tcp_url == 'securitytcp' && ionic.Platform.platform() == 'ios') {
                p_url += '?userPushToken=' + userPushToken;
            }
            httpService.query(p_url).then(function(res) {
                if (res.code == 200) {
                    q.resolve(res.data);
                    // 医生端测试
                    // q.resolve({ "ip": "139.196.211.234", "port": 2015 });
                }
            });
            return q.promise;
        };

        // zmq初始化
        init = function() {
            var platform, id, parms;
            platform = '_' + parseInt(Math.random() * 1000000);

            function connectZmq(id, token) {
                parms = {
                    id: (typeof id != 'string' ? id.toString() : id),
                    token: token,
                    timeout: zmq_timeout
                };
                getTcp(tcp_url).then(function(res_url) {
                    parms['url'] = res_url;
                    $timeout(function() {
                        window.ZMQPlugin.connect(parms, function(success) {
                            console.log('clent------初始化链接成功:' + JSON.stringify(success));
                            // receive_notification();
                        }, function(error) {
                            console.log('clent------初始化链接失败:' + JSON.stringify(error));
                        });
                    }, 100);
                });
            };

            if (user_id || $localStorage.ear_token) {
                tcp_url = 'securitytcp';
                id = user_id || $localStorage.user.userid;
                chat_token = $localStorage.ear_token;
                connectZmq(id, chat_token);
            } else {
                tcp_url = 'tcp';
                id = yk_id;
                chat_token = md5.createHash(ENV.token + random_id);
                connectZmq(id, chat_token);
            }

        };
        return {
            init: init
        };
    }
]);
